package it.francescogabbrielli.android.solidalapp.actions;

import android.util.Log;
import it.francescogabbrielli.android.solidalapp.Action;
import it.francescogabbrielli.android.solidalapp.Constants;
import it.francescogabbrielli.android.solidalapp.EndpointsUtils;
import it.francescogabbrielli.android.solidalapp.R;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.deviceendpoint.Deviceendpoint;
import it.francescogabbrielli.android.solidalapp.deviceendpoint.model.Device;
import it.francescogabbrielli.android.solidalapp.profileendpoint.Profileendpoint;
import it.francescogabbrielli.android.solidalapp.profileendpoint.model.Profile;

/**
 * Update profile data, and update the device with the phone number
 */
public class EndpointsUpdateProfile extends Action {
	
	private Profile profile;
	
	@Override
	public void execute() throws Exception {
		
		String tag = getClass().getSimpleName();
		
		Profile profile = getModel(Profile.class);
		String id = prefs.getString(Constants.PROFILE_ACCOUNT, "");
		if(profile==null || profile.getGoogleId()==null)
			return;
		
		Profileendpoint endpoint = EndpointsUtils.buildEndpoint(Profileendpoint.class);
//		
//		// check if profile already exists
//		if("".equals(id)) {
//			id = profile.getGoogleId();
//			profile = endpoint.getProfileByAccount(id).execute();
//			intent.putExtras(EndpointsUtils.toBundle(profile));
//			prefs.edit().putString(Constants.PROFILE_ACCOUNT, id).commit();
//		}
		
		// update profile data
		if("".equals(id)) {
			Log.w(tag, "Missing profile? "+profile);
			getIntent().putExtra(Constants.ERROR, "No account selected");
//			endpoint.insertProfile(profile).execute();
//			prefs.edit().putString(Constants.PROFILE_ACCOUNT, profile.getGoogleId()).commit();
		} else {
			this.profile = endpoint.updateProfile(profile).execute();
			setModel(this.profile);
		
			// update device if phone number changed...
			Device device = (Device) app.getData(DataKey.DEVICE);
			if(device!=null)
				try {
					EndpointsUtils.buildEndpoint(Deviceendpoint.class)
						.updateDevice(device).execute();
					Log.d(tag, "Device updated: "+device);
				} catch(Exception e) {
					Log.e(tag, "Error updating registered device "+device+": "+e, e);
				}
		}
		
	}

	@Override
	public void onPostExecute() throws Exception {
		if(profile!=null) {
			app.setData(DataKey.PROFILE, profile);
			app.alert(R.string.profile_updated);
		}
	}

}
